package 链表与双指针.m03.d21.t06;

import 链表与双指针.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0) {
            return null;
        }
        if(lists.length == 1) {
            return lists[0];
        }
        return f(lists, 0, lists.length-1);
    }
    private ListNode f(ListNode[] lists, int l, int r) {
        if(l==r) {
            return lists[l];
        }
        int m = (l+r)/2;
        ListNode LNode = f(lists, l, m);
        ListNode RNode = f(lists, m+1, r);
        ListNode res = merge(LNode, RNode);
        return res;
    }
    private ListNode merge(ListNode l, ListNode r) {
        ListNode head = new ListNode(), cur = head;
        while(l != null && r != null) {
            if(l.val < r.val) {
                head.next = l;
                l = l.next;
            } else {
                head.next = r;
                r = r.next;
            }
            head = head.next;
        }
        if(l != null) {
            head.next = l;
        }
        if(r != null) {
            head.next = r;
        }
        return cur.next;
    }
}